<?php

    /**
     * @package      Modules
     * @subpackage   Admins_Controllers_Admin
	 *
     * @license      GNU Lesser General Public Licence see LICENCE-LGPL file or http://www.gnu.org/licenses/lgpl.html
     */
    class Admins_Controllers_Admin_Logon extends Core_Controller_Action_Abstract
    {

	////////////////////////////////////////////////////////////////////////////
	//                                Variables                               //
	////////////////////////////////////////////////////////////////////////////

	    /**
	     * Parameters for plugins
	     *
	     * @var array
	     */
        protected $_pluginParams = array('*' => array('auth.required' => false));

        /**
         * Default namespace
         *
         * @var Zend_Session_Namespace
         */
        protected $_namespace = null;

	////////////////////////////////////////////////////////////////////////////
	//                                 Methods                                //
	////////////////////////////////////////////////////////////////////////////

        /**
         * Constructor
         *
         * @param       Core_Controller_Request_Abstract     $request
         */
        public function __construct(Core_Controller_Request_Abstract $request)
        {
            parent::__construct($request);

            $this->_namespace = new Zend_Session_Namespace('Default');
        }

        /**
         * Default action: display the login form
         *
         * @return      Core_Controller_Response_Abstract
         */
        public function index()
        {
            if ($this->_request instanceof Core_Controller_Request_Json) {
                $rep = $this->_getResponse('json');

                if (!Core_Authentification::isConnected()) {
                    $rep->setResponseException('sessionexpired');
                }

                return $rep;
            }
            
            $rep = $this->_getResponse('http');
            
            if ($this->_getParam('method') !== null) {
                $rep->setTemplate('json.tpl');
                $rep->data->assign('json', Zend_Json::encode(array('success' => false, 'errors' => 'sessionexpired', 'exception' => 'sessionexpired')));

            } else {
                $rep->setTemplate('login.tpl');
            }

            //$rep->data->assign('errors', $this->_namespace->errors);

            return $rep;
        }

        /**
         * Checks session validity
         *
         * @return      Core_Controller_Response_Abstract
         */
        public function check()
        {
            $rep = $this->_getResponse('json');

            if (!Core_Authentification::isConnected()) {
                $rep->setResponseException('sessionexpired');
                return $rep;
            }

            $authNamespace  = Core_Authentification::getNamespace();
            $aclok          = false;

            if (isset($authNamespace->authorized)) {
                $module = $this->_getParam('currentModule');

                foreach ($authNamespace->authorized as $package) {
                    foreach ($package['modules'] as $slug => $mod) {
                        if (strtolower($slug) == strtolower($module)) {
                            $aclok = true;
                            break;
                        }
                    }
                }
            }

            if (!$aclok) {
                $rep->setResponseException('permissiondenied');
                return $rep;
            }

            return $rep;
        }

        /**
         * Logs the user and redirects him to his initial request
         *
         * @return      Core_Controller_Response_Abstract
         */
        public function login()
        {
            $rep = $this->_getResponse('http');
            $rep->setTemplate('login.tpl');

            $authNamespace = Core_Authentification::getNamespace();

            $username = stripslashes($this->_getParam('login'));
            if (empty($username)) {
                $this->_namespace->errors = 'Erreur: Le login doit être renseigné.';
                return $rep;
            }

            $password = stripslashes($this->_getParam('password'));
            if (empty($password)) {
                $this->_namespace->errors = 'Erreur: Le mot de passe doit être renseigné.';
                return $rep;
            }

            $result = Core_Authentification::login($username, $password);

            if ($result->isValid()) {
                // security feature
                Zend_Session::regenerateId();

                // Raise event
                Core_Event::raise('UserLoggedIn');

                $rep = $this->_getResponse('redirect');
                $rep->setAction('core~index:index');
                return $rep;

            } else {
                /*
                switch ($result->getCode()) {
                    case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:
                        $this->_namespace->errors[] = 'Login doesn\'t exist';
                        break;

                    case Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS:
                        $this->_namespace->errors[] = 'Ambiguous login';
                        break;

                    case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:
                        $this->_namespace->errors[] = 'Invalid password';
                        break;

                    default:
                        $this->_namespace->errors[] = 'Erreur: Impossible de se connecter à la base de données.';
                        break;
                    }
                **/

                $this->_namespace->errors = 'Erreur: votre nom d\'utilisateur et votre mot de passe ne correspondent pas.';

            }

            $rep->data->assign('errors', $this->_namespace->errors);

            return $rep;
        }

        /**
         * Logs out the user and redirects him to the login form
         *
         * @return      Core_Controller_Response_Abstract
         */
        public function logout()
        {
            $rep = $this->_getResponse('redirect');

            Core_Authentification::logoff();
            $rep->setAction('admins~logon:index');

            return $rep;
        }
    }